package weather.util.dictionary;

import java.io.*;
import java.util.*;

import org.apache.poi.ss.usermodel.*;

/**
 * @author Jerzy Mazurek WEiTI PW
 */
public abstract class AbstractGroupingDictionary<Group, Element> extends AbstractDictionary
{
	public void loadFromXlsFile(File path, int sheetNumber) throws IOException
	{
		Workbook wb = openWorkbook(path);
		Sheet sheet = wb.getSheetAt(sheetNumber);
		
		int groupsRowNum = sheet.getFirstRowNum();
		
		Row groupsRow = sheet.getRow(groupsRowNum);
		int firstCellNum = groupsRow.getFirstCellNum();
		int lastCellNum = groupsRow.getLastCellNum();
		
		groups.clear();
		elements.clear();
		
		Map<Integer, Group> groupsMap = new HashMap<Integer, Group>(lastCellNum+1);
		
		for (int c = firstCellNum+1; c < lastCellNum; ++c)
		{
			Group group = newGroup(groupsRow.getCell(c).getStringCellValue());
			groups.add(group);
			groupsMap.put(c, group);
		}
		
		for (int r = groupsRowNum+1; r <= sheet.getLastRowNum(); ++r)
		{
			Row row = sheet.getRow(r);
			Element element = newElement(row.getCell(firstCellNum).getStringCellValue()); 
			
			elements.add(element);
			
			for (int c = firstCellNum+1; c < lastCellNum; ++c)
				if (row.getCell(c).getNumericCellValue() > 0.5)
					addToGroup(element, groupsMap.get(c));
		}
	}
	
	public boolean containsGroup(Group group)
	{
		return groups.contains(group);
	}
	
	public boolean containsElement(Element element)
	{
		return groups.contains(element);
	}
	
	public Set<Group> getGroups()
	{
		return groups;
	}

	public Set<Element> getElements()
	{
		return elements;
	}
	
	public abstract boolean groupContainsElement(Group group, Element element);
	public abstract boolean elementBelongsToGroup(Element element, Group group);
	
	protected abstract Group newGroup(String s);
	protected abstract Element newElement(String s);
	protected abstract void addToGroup(Element element, Group group);
	
	

	
	private Set<Group> groups = new HashSet<Group>();
	private Set<Element> elements = new HashSet<Element>();
}
